
/**
 * 执行sql: create,drop,insert,update,delete. 支持批量
 * @param {*} sqls 数据库操作语句数组
 * DEMO为数据库名
 * 存在数据库则删除 DROP TABLE IF EXISTS DEMO
 * 不存在数据库则创建 CREATE TABLE IF NOT EXISTS DEMO (id unique, data)
 * 插入数据 INSERT INTO DEMO (id, data) VALUES (1, "First row")
 * 更新数据 UPDATE DEMO SET data = "xxxx" WHERE id = "xxxx"
 * 删除数据 DELETE FROM DEMO WHERE id = "xxxx"
 * @param {*} success 成功返回
 * @param {*} fail 失败返回
 */
export function executeNonQuery (sqls, success, fail) {
    try {
        app.database.executeNonQuery(
            sqls,
            function(result){
                success(result);
            },
            function(e){
                fail(e);
            }
        );
    } catch (e) {
        fail(e);
    }
}

/**
 * 执行sql: select查询
 * @param {*} sql 数据库操作语句数组
 * DEMO为数据库名
 * 查询数据库 SELECT * FROM DEMO
 * @param {*} success 成功返回
 * @param {*} fail 失败返回
 */
export function executeQuery (sql, success, fail) {
    try {
        app.database.executeQuery(
            sql,
            function(result){
                success(result);
            },
            function(e){
                fail(e);
            }
        );
    } catch (e) {
        fail(e);
    }
}

/**************** 业务方法 ****************/
let rentalTaskTable = "RENTALHOUSETASK";
/**
 * 创建出租屋分级管理本地任务存储数据库
 * @param {*} successBack 成功返回
 * @param {*} failBack 失败返回
 * createRentalTaskTable(
        success => {
            console.log(success);
        },
        fail => {
            console.log(fail);
        },
    );
 */
export function createRentalTaskTable (successBack, failBack) {
    /**
     * 数据库字段说明
     * id，自动增长，默认值
     * userId，当前登录用户id
     * createTime, 创建时间
     * taskId，任务id，巡查【楼层是buildingFloor.id，房间是roomTask.id】，复查【roomTaskInfo.id】
     * taskType，任务类型，1楼层2房间；复查时直接使用taskType（reviewTaskType）
     * rentalType, 0：巡查，1：复查
     * rentalName，楼层任务【楼栋名+层数】，房间任务【楼栋名+房间名】
     * rentalAddress，楼层任务【楼栋地址+层数】，房间任务【楼栋地址+房间名】
     * rentalObject，界面显示数据实体json
     * inspectObject，inspectJson字符串保存
     */
    executeNonQuery(
        [
            `DROP TABLE IF EXISTS ${rentalTaskTable}`,
            // `CREATE TABLE IF NOT EXISTS ${rentalTaskTable} ` 
            //     + `(id unique, userId, createTime, taskId, taskType, rentalType, ` 
            //     + `rentalName, rentalAddress, rentalObject, inspectObject)`,
        ],
        success => {
            successBack(success);
        },
        fail => {
            failBack(fail);
        },
    );
}

/**
 * 插入出租屋分级管理本地任务数据
 * @param {*} obj 字段详情参见数据表创建
 * @param {*} successBack 
 * @param {*} failBack 
 * insertRentalTask(
        {
            userId: "guoyuanyuan",
            createTime: "2010-10-10",
            taskId: "e39fdfkl33jkj399",
            taskType: "2",
            rentalType: "0",
            rentalName: "更新任务",
            rentalAddress: "更新任务3df",
            rentalObject: "dldlld",
            inspectObject: "sdf",
        },
        success => {
            console.log(success);
        },
        fail => {
            console.log(fail);
        },
    );
 */
export function insertRentalTask (obj, successBack, failBack) {
    /**
     * 数据库字段说明
     * userId，当前登录用户id
     * createTime, 创建时间
     * taskId，任务id，巡查【楼层是buildingFloor.id，房间是roomTask.id】，复查【roomTaskInfo.id】
     * taskType，任务类型，1楼层2房间；复查时直接使用taskType（reviewTaskType）
     * rentalType, 0：巡查，1：复查
     * rentalName，楼层任务【楼栋名+层数】，房间任务【楼栋名+房间名】
     * rentalAddress，楼层任务【楼栋地址+层数】，房间任务【楼栋地址+房间名】
     * rentalObject，界面显示数据实体json
     * inspectObject，inspectJson字符串保存
     */
    let arr = Object.keys(obj);
    let keys = "";
    let values = "";
    if (arr.length > 0) {
        for (let i = 0; i < arr.length; i ++) {
            let key = arr[i];
            keys += ((i != 0 ? ", " : "") + key);
            values += ((i != 0 ? ", " : "") + '"' + obj[key]) + '"';
        }
    }
    let sql = `INSERT INTO ${rentalTaskTable} (${keys}) VALUES (${values})`;
    console.log(sql);
    executeNonQuery(
        [
            sql
        ],
        success => {
            successBack(success);
        },
        fail => {
            failBack(fail);
        },
    );
}

/**
 * 根据任务id更新本地任务数据
 * @param {*} taskId 
 * @param {*} obj 
 * @param {*} successBack 
 * @param {*} failBack 
 * updateRentalTask(
        "e39fdfkl33jkj399",
        {
            userId: "guoyuanyuan",
            createTime: "2010-10-10",
            taskId: "e39fdfkl33jkj399",
            taskType: "2",
            rentalType: "0",
            rentalName: "更新任务",
            rentalAddress: "更新任务3df",
            rentalObject: "dldlld",
            inspectObject: "sdf",
        },
        success => {
            console.log(success);
        },
        fail => {
            console.log(fail);
        },
    );
 */
export function updateRentalTask (taskId, obj, successBack, failBack) {
    let arr = Object.keys(obj);
    let changes = "";
    if (arr.length > 0) {
        for (let i = 0; i < arr.length; i ++) {
            let key = arr[i];
            changes += ((i != 0 ? ", " : "") + key + '="' + obj[key]) + '"';
        }
    }

    let sql = `UPDATE ${rentalTaskTable} SET ${changes} WHERE taskId="${taskId}"`;
    console.log(sql);
    executeNonQuery(
        [
            sql
        ],
        success => {
            successBack(success);
        },
        fail => {
            failBack(fail);
        },
    );
}

/**
 * 根据任务id删除本地任务数据
 * @param {*} taskId 
 * @param {*} successBack 
 * @param {*} failBack 
 * deleteRentalTaskByTaskId(
        "e39fdfkl33jkj399",
        success => {
            console.log(success);
        },
        fail => {
            console.log(fail);
        },
    );
 */
export function deleteRentalTaskByTaskId (taskId, successBack, failBack) {
    let sql = `DELETE FROM ${rentalTaskTable} WHERE taskId="${taskId}"`;
    console.log(sql);
    executeNonQuery(
        [
            sql
        ],
        success => {
            successBack(success);
        },
        fail => {
            failBack(fail);
        },
    );
}

/**
 * 删除本地所有任务数据
 * @param {*} successBack 
 * @param {*} failBack 
 */
export function deleteRentalAllTask (successBack, failBack) {
    let sql = `DELETE FROM ${rentalTaskTable}`;
    console.log(sql);
    executeNonQuery(
        [
            sql
        ],
        success => {
            successBack(success);
        },
        fail => {
            failBack(fail);
        },
    );
}

/**
 * 查询本地保存任务，没有userId则查询所有
 * @param {*} userId 
 * @param {*} successBack 
 * @param {*} failBack 
 * queryRentalTasksByUserId(
        "guoyuanyuan",
        success => {
            console.log(success);
        },
        fail => {
            console.log(fail);
        },
    );
 */
export function queryRentalTasksByUserId (userId, successBack, failBack) {
    let sql = `SELECT * FROM ${rentalTaskTable}`;
    if (userId) {
        sql += ` WHERE userId="${userId}"`;
    }
    console.log(sql);
    executeQuery(
        sql,
        success => {
            successBack(success);
        },
        fail => {
            failBack(fail);
        },
    );
}

export default {
    executeNonQuery,
    executeQuery,
    createRentalTaskTable,
    insertRentalTask,
    updateRentalTask,
    deleteRentalTaskByTaskId,
    deleteRentalAllTask,
    queryRentalTasksByUserId,
}